import { ref, reactive, onMounted } from "vue";

import { useRoute } from "vue-router";

import {
  queryCompanys,
  matchingPolicy,
  getPlanDetail
} from "../../service/matching";
import { ElMessage } from "element-plus";

export const usematchingHook = () => {
  const route: any = useRoute();

  const itemStatisticsList = ref<any>({});
  const normalStatisticsList = ref<any>({});
  const form = reactive({
    keyword: "",
    price: 0,
    name: ""
  });

  const companyID = ref<any>("");
  const planID = ref<any>("");

  interface LinkItem {
    value: string;
    link: string;
  }

  onMounted(() => {
    // 判断路由中是否带有规划参数
    const { id, name, companyId, scale } = route.query;
    if (id && name && companyId && scale) {
      // 请求图谱数据以及填充页面参数
      companyName.value = name;
      form.keyword = name;
      form.price = scale * 1;
      companyID.value = companyId;
      planID.value = id;
      // 规划
      getPlanDetail(id).then((res) => {
        if (res.code == 200) {
          // policyData.value = { id: "0", label: "政策图谱", children: [...JSON.parse(res.data.content)] };
          planUserID.value = res.data.userId;
          atlasTables.value = JSON.parse(res.data.content).policyList;
          let params = {
            policyList: res.data.content
          };
          localStorage.setItem("pdfData", res.data.content);
          console.log(atlasTables.value, "atlasTables.value");
          // console.log(JSON.parse(res.data.content))
          // atlasTables.value .forEach(item=>{
          //   item.policyList.forEach(val=>{
          //     val.url = 'http://'+window.location.host+'/detail?id='+val.policyId+'&searchType=2'
          //   })
          //   item.orgList.forEach(val=>{
          //     val.url = 'http://'+window.location.host+'/detail?id='+val.orgId+'&searchType=3'
          //   })
          // })
        }
      });
    }
  });

  const querySearchAsync = async (
    queryString: string,
    cb: (arg: any) => void
  ) => {
    const result = await queryCompanys(queryString);

    const results = result.data;
    if (results.length == 0) {
      form.name = form.keyword;
    }
    if (form.keyword.trim().length) {
      const filterRes = results.filter(
        (item: any) => item.name === form.keyword
      );

      if (!filterRes.length) {
        results.unshift({ id: "0", name: form.keyword });
      }
    }
    cb(results);
  };

  const handleSelect = (item: Record<string, any>) => {
    companyID.value = item.id;
  };

  const policyData = ref<any>();
  const planUserID = ref("");
  const atlasTables = ref([]);
  // const pdfData = ref({})
  const loading = ref(false);
  const companyName = ref("");
  const startMatching = async () => {
    localStorage.setItem("savePlanId", "");
    try {
      if (!companyID.value) {
        return ElMessage({
          message: "请选择单位后再进行匹配",
          type: "warning"
        });
      }
      loading.value = true;
      policyData.value = null;
      matchingPolicy({
        id: companyID.value,
        price: form.price,
        name: form.keyword
      }).then((res: any) => {
        if (res.code == 200) {
          policyData.value = {
            id: "0",
            label: "政策图谱",
            children: [...res.data.policyTreeList]
          };
          itemStatisticsList.value = res.data.itemStatisticsList;
          atlasTables.value = res.data.policyList;
          
          atlasTables.value.forEach((item) => {
          if(item.policyList){
            item.policyList.forEach((val) => {
              val.url =
                "http://" +
                window.location.host +
                "/detail?id=" +
                val.policyId +
                "&searchType=2";
            });
          }
            if(item.orgList){
              item.orgList.forEach((val) => {
                console.log(item,'item')
                val.url =
                  "http://" +
                  window.location.host +
                  "/detail?id=" +
                  val.orgId +
                  "&searchType=3";
              });
            }
          });
          localStorage.setItem("pdfData", JSON.stringify(res.data));
          normalStatisticsList.value = res.data.normalStatisticsList;
          companyName.value = form.keyword;
          loading.value = false;
        }
      });
    } catch (error) {
      // grouping用于隐藏多余提示框
      ElMessage({
        message: "服务端错误，请联系管理员",
        type: "error",
        grouping: true
      });
    }
  };

  const resetForm = () => {
    form.keyword = "";
    form.price = 0;
    companyID.value = "";
    planID.value = "";
    policyData.value = null;
  };
  return {
    normalStatisticsList,
    itemStatisticsList,
    form,
    handleSelect,
    querySearchAsync,
    startMatching,
    policyData,
    resetForm,
    companyID,
    planID,
    planUserID,
    loading,
    atlasTables,
    companyName
  };
};
